<?php

class WSB_Div
{

	/**
	 * Returns an array with all attributes of the input HTML tag as key/value pairs. Attributes are only lowercase a-z
	 * $tag is either a whole tag (eg '<TAG OPTION ATTRIB=VALUE>') or the parameterlist (ex ' OPTION ATTRIB=VALUE>')
	 * If a attribute is empty (I call it 'an option'), then the value for the key is empty. You can check if it existed with isset()
	 * Usage: 8
	 *
	 * @param	string		HTML-tag string (or attributes only)
	 * @return	array		Array with the attribute values.
	 */
	function get_tag_attributes($tag)	{
		$components = WSB_Div::split_tag_attributes($tag);
		$name = '';	 // attribute name is stored here
		$valuemode = '';
		if (is_array($components))	{
			while (list($key,$val) = each ($components))	{
				if ($val != '=')	{	// Only if $name is set (if there is an attribute, that waits for a value), that valuemode is enabled. This ensures that the attribute is assigned it's value
					if ($valuemode)	{
						if ($name)	{
							$attributes[$name] = $val;
							$name = '';
						}
					} else {
						if ($key = strtolower(ereg_replace('[^a-zA-Z0-9]','',$val)))	{
							$attributes[$key] = '';
							$name = $key;
						}
					}
					$valuemode = '';
				} else {
					$valuemode = 'on';
				}
			}
			if (is_array($attributes))	reset($attributes);
			return $attributes;
		}
	}

	/**
	 * Returns an array with the 'components' from an attribute list from an HTML tag. The result is normally analyzed by get_tag_attributes
	 * Removes tag-name if found
	 * Usage: 2
	 *
	 * @param	string		HTML-tag string (or attributes only)
	 * @return	array		Array with the attribute values.
	 * @internal
	 */
	function split_tag_attributes($tag)	{
		$tag_tmp = trim(eregi_replace ('^<[^[:space:]]*','',trim($tag)));
			// Removes any > in the end of the string
		$tag_tmp = trim(eregi_replace ('>$','',$tag_tmp));

		while (strcmp($tag_tmp,''))	{	// Compared with empty string instead , 030102
			$firstChar=substr($tag_tmp,0,1);
			if (!strcmp($firstChar,'"') || !strcmp($firstChar,"'"))	{
				$reg=explode($firstChar,$tag_tmp,3);
				$value[]=$reg[1];
				$tag_tmp=trim($reg[2]);
			} elseif (!strcmp($firstChar,'=')) {
				$value[] = '=';
				$tag_tmp = trim(substr($tag_tmp,1));		// Removes = chars.
			} else {
					// There are '' around the value. We look for the next ' ' or '>'
				$reg = split('[[:space:]=]',$tag_tmp,2);
				$value[] = trim($reg[0]);
				$tag_tmp = trim(substr($tag_tmp,strlen($reg[0]),1).$reg[1]);
			}
		}
		if (is_array($value))	reset($value);
		return $value;
	}

	/**
	 * Wandelt einen INI-String in ein mehrdimensionales Array um.
	 * Ein typischer INI-String sieht folgendermassen aus:
	 * type = list
	 * levelEntry = 2
	 * branchId = 31
	 * target = _blank
	 * level1.normal.wrap = <li>%s</li>
	 * level1.active.wrap = <li class="act">%s</li>
	 * level1.current.wrap = <li class="cur">%s</li>
	 * level1.wrap = <ul>%s</ul>
	 *
	 * @param string $ini
	 * @return array
	 */
	public static function iniToArray($ini)
	{
		$array = array();
		if(is_string($ini)) {
			$lines = explode("\n", $ini);
			$php = '';
			foreach($lines AS $line) {
				$line = trim($line);
				$pos = strpos($line, '=');
				if ($pos !== false) {
					$key = trim(substr($line, 0, $pos));
					$value = trim(substr($line, $pos+1));
					$keySegments = explode('.', $key);
					if(count($keySegments) > 0) {
						$php .= '$array';
						foreach($keySegments AS $segment) {
							$php .= "['" .$segment . "']";
						}
						$php .= "='" . $value . "';";
					}
				}
			}
			eval($php);
		}
		return $array;
	}


	/**
	 * Erstellt aus einem kommaseparierten String ein Index-Array und beruecksichtigt
	 * dabei, ob der String leer ist. Der Trenner muss uebergeben werden.
	 *
	 * @param string $csv
	 * @param string $delim
	 * @return array
	 */
	public static function csvToArray($csv, $delim)
	{
		$trimedCsv = trim($csv);
		$parts = explode($delim, $trimedCsv);
		if(count($parts) == 1) {
			if(empty($parts[0])) {
				$parts = array();
			}
		}
		return $parts;
	}

	/**
	 * PHP-Funktion explode mit zusaetzlicher Pruefung, ob der String leer ist.
	 *
	 * @param string $separator
	 * @param string $str
	 * @return array
	 */
	public static function explode($separator, $str)
	{
		$str = trim($str);
		if(!empty($str)) {
			$exploded = array();
			foreach(explode($separator, $str) AS $key=>$value) {
				$exploded[trim($key)] = trim($value);
			}
			return $exploded;
		} else {
			return array();
		}
	}

	/**
	 * Regulaerer Ausdruck zur Validierung von E-Mail-Adressen.
	 *
	 * @return string
	 */
	public static function getEmailRegex()
	{
		return '#^[A-Za-z0-9\._-]+[@][A-Za-z0-9\._-]+[\.].[A-Za-z0-9]+$#';
	}

	/**
	 * Test auf Gueltigkeit einer E-Mailadresse.
	 *
	 * @param string $email
	 * @return boolean
	 */
	public static function validEmail($email)	{
		$email = trim($email);
		if (strstr($email,' ')) return false;
		return preg_match(self::getEmailRegex(), $email) ? true : false;
	}

	/**
	 * Generiert ein Passwort in der angegebenen Laenge.
	 *
	 * @param integer $length
	 * @return string
	 */
	public static function generatePassword($length=4)
	{
	     $pattern = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	     $pattern .= "abcdefghijklmnopqrstuvwxyz";
	     $key = $pattern{rand(0,61)};
	     for($i=1;$i<$length;$i++) {
	         $key .= $pattern{rand(0,61)};
	     }
	     return $key;
	}

	/**
	 * Erstellt aus einer Zahl eine menschlich lesbare Groessenangabe.
	 *
	 * @param integer $size
	 * @return string
	 */
	public static function getHumanReadableFileSize($size)
	{
		$filesizename = array("&nbsp;Bytes", "&nbsp;KB", "&nbsp;MB", "&nbsp;GB", "&nbsp;TB", "&nbsp;PB", "&nbsp;EB", "&nbsp;ZB", "&nbsp;YB");
		if($size > 0) {
			$i = floor(log($size, 1024));
			$exponentialValue = pow(1024, ($i));
			$decimals = min(2, $i);
			return round($size/$exponentialValue, $decimals) . $filesizename[$i];
		} else {
			return 0 . $filesizename['0'];
		}
	}

	/**
	 * Ermittelt aus einem absoluten Dateipfad die Dateiendung.
	 *
	 * @param string $absFilePath
	 * @return string
	 */
	public static function getFileExtension($absFilePath)
	{
		$info = pathinfo($absFilePath);
		return $info['extension'];
	}

	/**
	 * @param string $file
	 * @return string
	 */
	public static function dirname($file)
	{
		$folder = dirname($file);
		if($folder == '.') {
			$folder = '';
		}
		return $folder;
	}

	/**
	 * @param string $path
	 * @return string
	 */
	public static function trimTrailingSlash($path)
	{
		return preg_replace('#/$#', '', $path);
	}

}
